package com.sqsxblog.navigation.fragment.view

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import com.sqsxblog.navigation.R

class SecondFragment : BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.fragment_second,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //尝试获取上一页传递的数据
        try {
            //用safeargs获取
            val bundle = SecondFragmentArgs.fromBundle(requireArguments())
            Toast.makeText(requireContext(),bundle.name+","+bundle.age,Toast.LENGTH_SHORT)
                .show()

            //不用safeargs获取
            Toast.makeText(requireContext(),
                "不用safeargs获取：" +
                        requireArguments().getString("name")+","+
                        requireArguments().getInt("age"),
                Toast.LENGTH_SHORT).show()

        } catch (e : Exception) {

        }

        requireView().findViewById<Button>(R.id.back).setOnClickListener {
            findNavController().navigateUp()
            //发送消息给firstFragment，模拟setResult
            Navigation
                .findNavController(requireView())
                .getBackStackEntry(R.id.firstFragment)  //上一个栈的id
                .savedStateHandle
                .getLiveData<String>("key") //这个泛型你可以传其他对象，例如Intent
                .value = "我要传值"
        }
        //由第二页打开第三页
        requireView().findViewById<Button>(R.id.jump).setOnClickListener {
            findNavController().navigate(R.id.action_secondFragment_to_thirdFragment)
        }
    }
}